package dao

import (
	"yundian/internel/app/models/devploys"
	"yundian/internel/app/models/ploys"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
)

type PloysDao struct {
}

func NewPloysDao() *PloysDao {
	return &PloysDao{}
}

// GetDevicePloyInfo 获取设备类型的奖励规则
func (dao *PloysDao) GetDevicePloyInfo(deviceType int) *dingo.ErrorWrap {
	m := devploys.New()
	sql := `select * from device_ploys where type_id = ?`
	db := global.Orm.Debug().Raw(sql, deviceType).Find(&m)
	return dingo.ErrorIf(db.Error, m)
}

// GetPloys 获取奖励规则列表By place_id,device_type_id
func (dao *PloysDao) GetPloys(placeId, deviceTypeId int) *dingo.ErrorWrap {
	var lst []devploys.DevicePloysModel
	sql := `select * from ploys where place_id = ? and type_id = ? order by create_at desc`
	db := global.Orm.Raw(sql, placeId, deviceTypeId).Find(&lst)
	return dingo.ErrorIf(db.Error, lst)
}

// InsertPlacePloys 新增商户的奖励规则
func (dao *PloysDao) InsertPlacePloys(m *ploys.PloyModel) *dingo.ErrorWrap {
	db := global.Orm.Debug().Table("ploys").Create(m)
	return dingo.ErrorIf(db.Error, true)
}

// SavePlacePloys 保存商户的奖励规则
func (dao *PloysDao) SavePlacePloys(m *ploys.PloyModel) *dingo.ErrorWrap {
	db := global.Orm.Debug().Table("ploys").Where("id = ?", m.Id).Model(&m).Updates(m)
	return dingo.ErrorIf(db.Error, true)
}

func (dao *PloysDao) SavePlacePloyByPlaceId(m *ploys.PloyModel) *dingo.ErrorWrap {
	db := global.Orm.Debug().Table("ploys").Where("place_id = ?", m.PlaceId).Model(&m).Updates(m)
	return dingo.ErrorIf(db.Error, true)
}

//  获取商户奖励规则详情By place_id,shared_mode
func (dao *PloysDao) GetPlacePloyInfoByPaceIdAndMode(placeId int, sharedMode string) *dingo.ErrorWrap {
	m := ploys.New()
	sql := "select * from ploys where place_id = ? and shared_mode = ? and `type` != 0 and `range` != 0 and num != 0 order by id DESC limit 1"
	db := global.Orm.Raw(sql, placeId, sharedMode).Find(&m)
	return dingo.ErrorIf(db.Error, m)
}

// 获取网点奖励规则
func (dao *PloysDao) GetPlacePloyInfo(placeId int, sharedMode string) *dingo.ErrorWrap {
	m := ploys.New()
	sql := `select * from ploys where place_id = ? and shared_mode = ? order by create_at desc limit 1`
	db := global.Orm.Raw(sql, placeId, sharedMode).Find(&m)
	return dingo.ErrorIf(db.Error, m)
}

// 获取运营商奖励规则
func (dao *PloysDao) GetUserPloyInfo(userId int, sharedMode string) *dingo.ErrorWrap {
	m := ploys.New()
	sql := `select * from ploys where user_id = ? and shared_mode = ? order by create_at desc limit 1`
	db := global.Orm.Raw(sql, userId, sharedMode).Find(&m)
	return dingo.ErrorIf(db.Error, m)
}